<template>
  <el-row :gutter="15">
    <el-col :span="24">
      <el-card class="search-form">
        <el-form ref="searchForm" class="el-form-col" :model="search">
          <el-row :gutter="15" style="position:relative;">
            <el-col :lg="4" :md="6">
              <el-form-item prop="orderNo" style="position: relative">
                <el-input v-model="search.orderNo" type="textarea" :rows="4" placeholder="订单号  (支持多单查询，用英文逗号分隔)"
                          clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="outOrderNo" style="position: relative">
                <el-input v-model="search.outOrderNo" type="textarea" :rows="4" placeholder="推单单号  (支持多单查询，用英文逗号分隔)"
                          clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="consigneeName">
                <el-input v-model="search.consigneeName" placeholder="客户姓名" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6" class="hidden-lg-only hidden-xl-only">
              <el-form-item>
                <el-row class="search-btns" :gutter="5">
                  <el-col :span="8">
                    <el-button type="primary" :loading="searchLoading" plain native-type="submit" @click.prevent="searchFunc(search)"><span>搜索</span></el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button type="primary" plain @click="isOpen = !isOpen">{{ isOpen ? '收起' : '展开' }}</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button @click="resetFields" plain>重置</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="consigneePhone">
                <el-input v-model="search.consigneePhone" placeholder="客户电话" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="businessNo">
                <el-select v-model="search.businessNo" clearable placeholder="业务类型">
                  <el-option
                    v-for="item in businessArr"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6" class="hidden-md-only hidden-sm-only">
              <el-form-item>
                <el-row class="search-btns" :gutter="5">
                  <el-col :span="8">
                    <el-button type="primary" :loading="searchLoading" plain @click="searchFunc(search)"><span>搜索</span></el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button type="primary" plain @click="isOpen = !isOpen">{{ isOpen ? '收起' : '展开' }}</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button @click="resetFields" plain>重置</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="serviceNo">
                <el-select v-model="search.serviceNo" clearable placeholder="服务类型">
                  <el-option
                    v-for="item in serviceArr"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="wokerUserName">
                <el-input v-model="search.wokerUserName" placeholder="服务方" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="sourceWarehouse">
                <el-input v-model="search.sourceWarehouse" placeholder="推单来源" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item prop="address">
                <cascade-address :level="3" changeOnSelect v-model="search.address" placeholder="客户地址:省/市/区"></cascade-address>
              </el-form-item>
            </el-col>
            <div v-show="isOpen">
              <el-col :lg="4" :md="6">
                <el-form-item prop="foundName">
                  <el-input v-model="search.foundName" placeholder="导入人" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item prop="startFoundDate">
                  <el-date-picker type="date"
                                  placeholder="导入开始日期"
                                  value-format="yyyy-MM-dd"
                                  v-model="search.startFoundDate" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item prop="endFoundDate">
                  <el-date-picker type="date"
                                  placeholder="导入结束日期"
                                  v-model="search.endFoundDate"
                                  value-format="yyyy-MM-dd"
                                  :picker-options="{disabledDate}" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
            </div>
          </el-row>
        </el-form>
      </el-card>
    </el-col>
    <el-col :span="24">
      <BasicTable
        ref="BasicTable"
        url="/ms-fahuobao-order/FhbOrderTemp/findFhbOrderTempAll"
        :columns="columns"
        :tabs="tabs"
        :showButtonGroup="false"
        @selection-change="selectionChange"
      >
        <template slot="preColumn">
          <el-table-column prop="orderNo" fixed="left" width="170px" align="center" label="订单号">
            <template slot-scope="scope">
              <a href="javascript:;" class="blue-color" @click="show(scope.row)">{{ scope.row.orderNo }}</a>
            </template>
          </el-table-column>
        </template>
        <template slot="column">
          <el-table-column fixed="right" width="80px" align="center" label="操作">
            <template slot-scope="scope">
              <el-button v-if="orderType == 1"
                size="mini"
                type="text"
                @click="show(scope.row)"
              ><span>确认转正</span></el-button>
              <el-button v-else
                size="mini"
                type="text"
                @click="show(scope.row)"
              ><span>再次下单</span></el-button>
            </template>
          </el-table-column>
        </template>
        <template slot="buttons">
          <el-button  @click.prevent="importModal">导入订单</el-button>
          <el-button  @click.prevent="importResult">导入结果</el-button>
          <el-button  @click.prevent="delData" type="danger" >删除订单</el-button>
          <el-button  @click.prevent="batchHandle" type="primary" >批量提交</el-button>
        </template>
      </BasicTable>
      <ImportExcelModal :visible.sync="visible" fileType="orderTemp" title="导单"
                        :downLoadUrl="api + '/ms-fahuobao-order/FhbOrder/excelDownload'"
                        :url="'/zuul/ms-common-excelupload/excel/fileImport'"
      >
        <div slot="tips" class="col-xs-12 m--margin-top-10">
          <div class="alert alert-danger show text-center">
            由于上传文件转换为订单需要时间处理，上传后文件处理情况请在处理结果中查看，文件处理成功后订单将进入暂存单列表。
          </div>
        </div>
      </ImportExcelModal>
      <ImportResult ref="ImportResult" :visible.sync="visibleResult" :url="'/ms-common-excelupload/excel/getRecentlyData'"></ImportResult>
    </el-col>
  </el-row>
</template>
<script>
import {filterDataBaseDictionary, unixTimestampFilter, filterSecond} from '@/filters'
import {getFhbServiceType, getFhbOrderSource, getSubDictListOfParentCode} from '@/utils/selectOptions'
import {copy, alert, dotData, confirm} from '@/utils'
import moment from 'moment'
import ImportExcelModal from '@/views/oms/ImportExcelModal'
import ImportResult from '@/views/business/ImportResult'
import {dataServiceConfig} from '@/config/index.js'
import StompJs from '@/utils/StompJs'
import {getUserInfo} from '@/utils/auth.js'
export default {
  name: 'faTemporaryIndex',
  components: {
    ImportExcelModal,
    ImportResult
  },
  filters: {
    filterDataBaseDictionary,
    unixTimestampFilter,
    filterSecond
  },
  data() {
    let that = this
    let columns = [
      {
        label: '推单来源',
        data: 'sourceWarehouse'
      },
      {
        label: '推单单号',
        data: 'outOrderNo'
      },
      {
        label: '业务类型',
        data: 'businessNo',
        render(data, type, full, meta) {
          return filterDataBaseDictionary(data)
        }
      },
      {
        label: '服务类型',
        data: 'service'
      },
      {
        label: '服务方',
        data: 'wokerUserName'
      },
      {
        label: '服务方电话',
        data: 'wokerPhone'
      },
      {
        label: '服务费',
        data: 'wokerPrice'
      },
      {
        label: '客户姓名',
        data: 'consigneeName'
      },
      {
        label: '客户电话',
        data: 'consigneePhone'
      },
      {
        label: '客户地址',
        data: 'province',
        render(data, type, full, meta) {
          return `${full.row.province} ${full.row.city} ${full.row.district}`
        }
      },
      {
        label: '商品总数',
        data: 'allCount'
      },
      {
        label: '总包件',
        data: 'allPackages'
      },
      {
        label: '总体积(m³)',
        data: 'allVolume'
      },
      {
        label: '总重量(kg)',
        data: 'allWeight'
      },
      {
        label: '导入日期',
        data: 'founderTime',
        render(data, type, full, meta) {
          return unixTimestampFilter(data, 'YYYY-MM-DD')
        }
      }
    ]
    return {
      userId: getUserInfo('id'),
      api: dataServiceConfig.urlPrefix,
      visible: false,
      visibleResult: false,
      subOrderFinish: '',
      params: {
        pageSize: 10,
        pageNum: 1
      },
      isOpen: false,
      searchLoading: false,
      checkedData: [],
      search: {
        orderNo: '',
        outOrderNo: '',
        consigneeName: '',
        consigneePhone: '',
        businessNo: '',
        serviceNo: '',
        wokerUserName: '',
        sourceWarehouse: '',
        foundName: '',
        startFoundDate: '',
        endFoundDate: ''
      },
      businessArr: [],
      serviceArr: [],
      orderSourceArr: [],
      orderType: 1,
      checkOrderArr: [],
      columns: columns,
      tabs: [
        {
          label: '待转正',
          columns: columns,
          callback(params) {
            params.orderType = 1
            that.orderType = 1
          }
        },
        {
          label: '已取消',
          columns: columns,
          callback(params) {
            params.orderType = 2
            that.orderType = 2
          }
        }
      ]
    }
  },
  created() {
    getFhbServiceType().then(data => {
      this.serviceArr = data
    })
    getSubDictListOfParentCode('BSTE').then(data => {
      this.businessArr = data
    })
    getFhbOrderSource().then(data => {
      this.orderSourceArr = data
    })
    let s1 = new StompJs()
    s1.subscribe('/topic/' + this.userId + 'orderFinish', (message) => {
      this.searchFunc()
    }).then(sub => {
      this.subOrderFinish = sub
    })
  },
  destroyed() {
    if (this.subOrderFinish) {
      this.subOrderFinish.unsubscribe()
    }
  },
  methods: {
    disabledDate(time) {
      return time.getTime() < moment(this.search.allocationStartTime).format('x')
    },
    selectionChange(arr) {
      this.checkedData = arr
    },
    importModal() {
      this.visible = true
    },
    importResult() {
      this.visibleResult = true
    },
    searchFunc() {
      const basicTable = this.$refs.BasicTable
      if (basicTable) {
        let data = copy(this.search)
        data.provinceNo = dotData(data.address, '[0]') || ''
        data.cityNo = dotData(data.address, '[1]') || ''
        data.districtNo = dotData(data.address, '[2]') || ''
        delete data.address
        this.searchLoading = true
        basicTable.search(data).finally(_ => {
          this.searchLoading = false
        })
      }
    },
    delData() {
      if (!this.checkedData.length) {
        alert('请选择要删除的订单！', '提示', 'warning')
        return
      }
      let delOrderIdArr = []
      this.checkedData.forEach(item => {
        delOrderIdArr.push(item.id)
      })
      confirm('此操作将永久删除该订单，是否继续？', '提示', {
        confirmButtonLoading: true,
        dangerouslyUseHTMLString: true,
        showCancelButton: true,
        confirmCallBack: ({confirmButtonLoadingClose, close}) => {
          this.$ajax.post('/ms-fahuobao-order/FhbOrder/deleteOrder', {orderIds: delOrderIdArr.join(',')}).then(response => {
            if (response.success) {
              close()
              alert('操作成功！', '', 'success')
              this.searchFunc()
            }
            confirmButtonLoadingClose()
          }).catch(_ => {
            confirmButtonLoadingClose()
          })
        }
      })
    },
    show(data) {
      this.$router.push({path: '/ss-fhb/fa-temporary/show/' + data.id})
    },
    batchHandle() {
      if (!this.checkedData.length) {
        alert('请选择要操作的订单！', '提示', 'warning')
        return
      }
      let orderIds = []
      this.checkedData.forEach(item => {
        orderIds.push(item.id)
      })
      confirm(`你已选择 <span style="color: red;">${orderIds.length}</span> 单，确认全部${(this.orderType === 1) ? '转正' : '再次下单'}？`, '温馨提示', {
        confirmButtonLoading: true,
        dangerouslyUseHTMLString: true,
        showCancelButton: true,
        confirmCallBack: ({confirmButtonLoadingClose, close}) => {
          this.$ajax.post('/ms-fahuobao-order/FhbOrder/saveBathOrder', {ids: orderIds}).then(response => {
            if (response.success) {
              close()
              alert('操作成功！', '', 'success')
              this.searchFunc()
            }
            confirmButtonLoadingClose()
          }).catch(_ => {
            confirmButtonLoadingClose()
          })
        }
      })
    },
    // 重置表单
    resetFields() {
      const searchForm = this.$refs.searchForm
      if (searchForm) {
        searchForm.resetFields()
      }
    }
  }
}
</script>
